import os
import sys
from flask import Flask, request, send_file, jsonify
from flask_cors import CORS
from dotenv import load_dotenv
from pathlib import Path
import tempfile
import traceback
import requests
import time
import uuid

# 加载环境变量
load_dotenv()
OPENAI_KEY = os.getenv("OPENAI-KEY")
HTTP_PROXY = os.getenv("HTTP_PROXY")
HTTPS_PROXY = os.getenv("HTTPS_PROXY")

# 设置代理环境变量（加载但不设置全局环境变量，避免影响OpenAI SDK）
proxy_config = {}
if HTTP_PROXY:
    proxy_config["http"] = HTTP_PROXY
    print(f"HTTP代理配置: {HTTP_PROXY}")
if HTTPS_PROXY:
    proxy_config["https"] = HTTPS_PROXY
    print(f"HTTPS代理配置: {HTTPS_PROXY}")

# 清除可能导致冲突的环境变量
if "http_proxy" in os.environ:
    del os.environ["http_proxy"]
if "https_proxy" in os.environ:
    del os.environ["https_proxy"]
if "HTTP_PROXY" in os.environ:
    del os.environ["HTTP_PROXY"]
if "HTTPS_PROXY" in os.environ:
    del os.environ["HTTPS_PROXY"]

app = Flask(__name__)
CORS(app)  # 启用CORS支持

def check_proxy_connection():
    """检查代理连接是否正常工作"""
    proxy_url = HTTP_PROXY or HTTPS_PROXY
    if not proxy_url:
        return False, "未配置代理"
        
    try:
        # 尝试通过代理连接到一个常用网站
        test_url = "https://www.google.com"
        proxies = proxy_config
        
        print(f"正在通过代理 {proxy_url} 测试连接...")
        response = requests.get(test_url, proxies=proxies, timeout=5)
        return True, f"代理连接正常，HTTP状态: {response.status_code}"
    except Exception as e:
        return False, f"代理连接失败: {str(e)}"

@app.route('/api/openai-tts', methods=['POST'])
def openai_tts():
    try:
        data = request.json
        if not data:
            return jsonify({"error": "Missing request body"}), 400
            
        text = data.get("input")
        model = data.get("model", "tts-1")
        voice = data.get("voice", "alloy")
        response_format = data.get("response_format", "mp3")
        speed = data.get("speed", 1.0)
        
        if not text:
            return jsonify({"error": "Missing input text"}), 400

        # 调试信息
        print(f"Processing request: model={model}, voice={voice}, format={response_format}")
        
        if not OPENAI_KEY:
            return jsonify({"error": "OpenAI API key not found. Please set OPENAI-KEY in .env file"}), 500

        # 创建带有唯一名称的临时文件，避免冲突
        unique_id = str(int(time.time())) + '_' + str(os.getpid())
        temp_dir = tempfile.gettempdir()
        filepath = os.path.join(temp_dir, f"speech_{unique_id}.{response_format}")
        
        try:
            # 注意: 不要在环境中设置代理，而是使用requests直接请求OpenAI的API
            print(f"开始调用OpenAI API... 临时文件: {filepath}")
            
            # 直接使用requests调用OpenAI API，这样可以显式地传递代理
            api_url = f"https://api.openai.com/v1/audio/speech"
            headers = {
                "Authorization": f"Bearer {OPENAI_KEY}",
                "Content-Type": "application/json"
            }
            payload = {
                "model": model,
                "input": text,
                "voice": voice,
                "response_format": response_format,
                "speed": float(speed)
            }
            
            print(f"发送请求到 OpenAI API，使用代理: {proxy_config}")
            response = requests.post(
                api_url,
                headers=headers,
                json=payload,
                proxies=proxy_config if proxy_config else None,
                timeout=60
            )
            
            if response.status_code != 200:
                raise Exception(f"OpenAI API 返回错误: {response.status_code} - {response.text}")
            
            # 保存响应内容到临时文件
            with open(filepath, "wb") as f:
                f.write(response.content)
                
            print(f"API调用成功，音频已保存到: {filepath}")
            
            # 等待一小段时间确保文件写入完成
            time.sleep(0.2)
            
            # 使用send_file发送文件
            return send_file(
                filepath, 
                mimetype=f'audio/{response_format}', 
                as_attachment=True,
                download_name=f'speech.{response_format}'
            )
            
        except Exception as e:
            error_msg = str(e)
            print(f"API调用失败: {error_msg}")
            # 记录详细错误
            traceback.print_exc()
            
            # 尝试安全删除临时文件（如果存在且可访问）
            try:
                if os.path.exists(filepath):
                    os.remove(filepath)
            except Exception as del_err:
                print(f"警告：无法删除临时文件 {filepath}: {str(del_err)}")
                
            return jsonify({"error": error_msg}), 500
                
    except Exception as e:
        error_trace = traceback.format_exc()
        print(f"Error in openai-tts: {str(e)}\n{error_trace}")
        
        return jsonify({"error": str(e), "trace": error_trace}), 500

@app.route('/api/openai-tts/test', methods=['GET'])
def test_endpoint():
    # 测试网络连接和代理设置
    try:
        # 检查代理连接
        proxy_ok, proxy_msg = check_proxy_connection()
        
        # 测试OpenAI API
        print("测试与OpenAI的连接...")
        try:
            # 使用相同方式测试API连接
            resp = requests.get(
                "https://api.openai.com/v1/models", 
                headers={"Authorization": f"Bearer {OPENAI_KEY}"},
                proxies=proxy_config if proxy_config else None,
                timeout=10
            )
            openai_status = resp.status_code
            openai_response = resp.text if resp.status_code != 200 else "OK"
            openai_available = resp.status_code == 200
        except Exception as e:
            openai_status = 0
            openai_response = str(e)
            openai_available = False
            
        # 尝试使用requests直接调用Speech API
        speech_test_ok = False
        speech_test_msg = "未测试"
        try:
            test_api_url = "https://api.openai.com/v1/audio/speech"
            test_headers = {
                "Authorization": f"Bearer {OPENAI_KEY}",
                "Content-Type": "application/json"
            }
            test_payload = {
                "model": "tts-1",
                "input": "Hello, this is a test.",
                "voice": "alloy"
            }
            
            speech_resp = requests.post(
                test_api_url,
                headers=test_headers,
                json=test_payload,
                proxies=proxy_config if proxy_config else None,
                timeout=15
            )
            
            if speech_resp.status_code == 200:
                speech_test_ok = True
                speech_test_msg = f"成功，返回音频大小: {len(speech_resp.content)} 字节"
            else:
                speech_test_msg = f"失败，状态码: {speech_resp.status_code}, 内容: {speech_resp.text}"
        except Exception as e:
            speech_test_msg = f"异常: {str(e)}"
            
        return jsonify({
            "status": "OpenAI TTS API is running",
            "connection_test": "success" if openai_available else "failed",
            "proxy_config": proxy_config,
            "proxy_working": proxy_ok,
            "proxy_message": proxy_msg,
            "openai_available": openai_available,
            "openai_status_code": openai_status,
            "openai_response": openai_response,
            "speech_api_test": "success" if speech_test_ok else "failed",
            "speech_api_message": speech_test_msg
        }), 200
        
    except Exception as e:
        return jsonify({
            "status": "OpenAI TTS API is running",
            "connection_test": "error",
            "proxy_config": proxy_config,
            "proxy_working": False,
            "proxy_message": "代理测试失败",
            "error": str(e)
        }), 200

if __name__ == "__main__":
    print(f"OpenAI TTS server starting on port 5001...")
    print(f"API密钥状态: {'已设置' if OPENAI_KEY else '未设置'}")
    print(f"HTTP代理: {HTTP_PROXY or '未设置'}")
    print(f"HTTPS代理: {HTTPS_PROXY or '未设置'}")
    
    # 检查代理连接
    proxy_working, proxy_message = check_proxy_connection()
    print(f"代理状态: {'正常' if proxy_working else '异常'} - {proxy_message}")
    
    print(f"测试服务: curl http://localhost:5001/api/openai-tts/test")
    app.run(host='0.0.0.0', port=5001, debug=True)
